import KBEngine
import KBEDebug as log
import json
import Functor
import hashlib
# from WXBizDataCrypt import WXBizDataCrypt

# app id: wx3ffeebe9ddbe3d45
# app secret: 7da0329b5ded0d65ec04212ff7a253ce
appId = "wx2629615d1f23258d"
appSecret = "60736370b56046b41358161a8c9a3fa3"
headers = {
    "Content-Type": "application/json"
}


def onRequestAccountLogin(loginName, password, datas):
    # 压测
    if "bot_" in loginName:
        KBEngine.accountLoginResponse(loginName, loginName, datas, KBEngine.SERVER_SUCCESS)
        return

    sdata = str(datas, encoding='utf-8')
    log.INFO_MSG(f'onRequestAccountLogin: loginName:{loginName} password:{password} datas:{datas}')
    jdata = json.loads(sdata)
    log.INFO_MSG(f'jdata: {jdata}')
    # 作为一个key缓存在C++层，调用accountLoginResponse会根据这个key去查找账号
    commitName = loginName

    # 此处可通过http等手段将请求提交至第三方平台，平台返回的数据也可放入datas
    # datas将会回调至客户端
    # 如果使用http访问，因为interfaces是单线程的，同步http访问容易卡住主线程，建议使用
    # KBEngine.registerReadFileDescriptor()和KBEngine.registerWriteFileDescriptor()结合
    # KBEngine.urlopen("https://www.baidu.com",onHttpCallback)异步访问。也可以结合socket的方式与平台交互。

    # 如果返回码为KBEngine.SERVER_ERR_LOCAL_PROCESSING则表示验证登陆成功，但dbmgr需要检查账号密码，KBEngine.SERVER_SUCCESS则无需再检查密码
    if jdata['platform'] == 'wx':
        # pc = WXBizDataCrypt(jdata['appId'], jdata['sessionKey'])

        # """
        #     {
        #         'openId': 'oGZUI0egBJY1zhBYw2KhdUfwVJJE',
        #         'nickName': 'Band',
        #         'gender': 1,
        #         'language': 'zh_CN',
        #         'city': 'Guangzhou',
        #         'province': 'Guangdong',
        #         'country': 'CN',
        #         'avatarUrl': 'http://wx.qlogo.cn/mmopen/vi_32/aSKcBBPpibyKNicHNTMM0qJVh8Kjgiak2AHWr8MHM4WgMEm7GFhsf8OYrySdbvAMvTsw3mo8ibKicsnfN5pRjl1p8HQ/0',
        #         'unionId': 'ocMvos6NjeKLIBqg5Mr9QjxrP1FA',
        #         'watermark': {'timestamp': 1477314187, 'appid': 'wx4f4bc4dec97d474b'}
        #     }
        # """
        # info = pc.decrypt(jdata['encryptedData'], jdata['iv'])
        # datas = json.dumps(info).encode('utf-8')
        # log.DEBUG_MSG(info)
        code = jdata['code']
        url = f'https://api.weixin.qq.com/sns/jscode2session?appid={appId}&secret={appSecret}&js_code={code}&grant_type=authorization_code'

        KBEngine.urlopen(url, Functor.Functor(onHttpCallback, commitName))
        # KBEngine.accountLoginResponse(commitName, realAccountName, datas, KBEngine.SERVER_ERR_LOCAL_PROCESSING)
    else:
        # 默认账号名就是提交时的名
        realAccountName = commitName
        KBEngine.accountLoginResponse(commitName, realAccountName, datas, KBEngine.SERVER_SUCCESS)


def onHttpCallback(commitName, httpcode, data, headers, success, url):
    log.INFO_MSG(f'onHttpCallback {data}')
    jdata = json.loads(data)
    log.INFO_MSG(f'onHttpCallback: {httpcode} {data} {success}')
    if 'openid' not in jdata:
        KBEngine.accountLoginResponse(commitName, commitName, b'', KBEngine.SERVER_ERR_USER1)
        return

    if httpcode == 200:
        openid = jdata['openid']
        KBEngine.accountLoginResponse(commitName, openid, b'', KBEngine.SERVER_SUCCESS)
    else:
        log.ERROR_MSG(f'onHttpCallback {httpcode} {data} {headers} {url}')
        KBEngine.accountLoginResponse(commitName, openid, b'', KBEngine.SERVER_SUCCESS)
    # print(httpcode, data, headers, success, url)
